<?php
namespace control;


class saleSendOrderInvoiceClass extends adIndexClass
{
    private const page = 'saleSendOrderInvoice';
    private const title = '销项发票';
    private const table   = 'sale_send_order_invoice';
    private const tableMx = 'sale_send_order_invoice_detail';
    private const status = ['草稿','审批中','已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'companyName'          => [
                        'name'  => '客户名称',
                        'width' => 100,
                    ],
                    'type'          => [
                        'name'  => '发票类型',
                        'width' => 100,
                    ],
                    'invoiceNo'          => [
                        'name'  => '发票编号',
                        'width' => 100,
                    ],
                    'money'          => [
                        'name'  => '开票金额',
                        'width' => 100,
                    ],
                    'rate'          => [
                        'name'  => '税率',
                        'width' => 150,
                    ],
                    'taxMoney'          => [
                        'name'  => '税额',
                        'width' => 150,
                    ],
                    'invoiceDate'          => [
                        'name'  => '开票日期',
                        'width' => 150,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 150,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ],
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号"   => text(array("name" => "orderNo")),
                ],
                [
                    '客户'  => clientProfileClass::kehuSelect(array('title' => '')),
                    '单据日期' => text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
//                    "状态" => select(["name" => "classify", 'option' => ['采购付款', '采购退款','核销','付款单核销']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url    = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            'khid' =>  $this->post('khid'),
            'orderNo' =>  $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        $and = "";
        if ($this->post('recordDate')) {
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'targetDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table,'field'=>"*",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "companyName":
                        $kehu  = query('kehu', "khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id   = $this->get('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[]    = [
            "name"  => '保存',
            "type"  => "点击事件",
            "title" => '保存',
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $tr[]        = ['', '产品编码', '产品名称', '规格型号', '单位', '单价', '发货数量', '金额', '本次开票金额', '备注' , '关联单据'];
        $opportunity = [];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]'"));
        foreach ($result['array'] as $k=>$array) {
            $material = query('material', " id = '$array[materialId]'");
            $orderNo = "";
            if($array['sourceTable']){
                $sale_send_order  = query($array['sourceTable'], "id = '$array[saleOrderId]'");
                $orderNo = $sale_send_order['orderNo'];
            }
            $tr[]     = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'sourceTable[]', 'value' => $array['sourceTable'])) .
                hidden(array('name' => 'saleOrderId[]', 'value' => $array['saleOrderId'])) .
                hidden(array('name' => 'materialId[]', 'value' => $material['id'])),
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                $array['price'],
                $array['num'],
                $array['orderMoney'],
                text(array('name' => 'money[]', 'value' => $array['money'] ? self::lostZero($array['money'], 'pricePrecision') : '')),
                text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
                $orderNo
            ];
        }
        $list  = $this->listTable(array('tr' => $tr, 'end' => true));
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    "客户："    => clientClass::kehuSelect(array('value' => $this->get('khid') ?: ($opportunity['khid'] ?? $info['khid']))),
                    "开票金额："    => $info['money'],
                ],
                [
                    "开票日期："  => text(["name" => "invoiceDate", 'class' => 'text', 'laydate' => [], "value" => $info['invoiceDate']]),
                    "发票类型：" => radio(["name" => "type", "value" => ['专票','普票'], "checked" => $info['type']])
                ],
                [
                    "发票编号："      => text(["name" => "invoiceNo", 'class' => 'text', "value" => $info['invoiceNo']]),
                    "税率："      => text(["name" => "rate", 'class' => 'text', "value" => $info['rate']]),
                ],
                [
                    "税额：" => $info['taxMoney'],
                    "备注：" => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ]
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => "",
            'button' => "<span class=\"smallButton\" onclick=\"layer('{$this->get('cla')}','addMx',$('form[name=quotationsEditForm]').serialize())\">获取发货单明细</span>",
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
        ]);
        $data['html'] .= <<<efo
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}
</script>
efo;
        //返回
        return $this->tab($data);
    }

    public function editEdit()
    {
        $id              = $this->post('id') ?: self::getId();
        $mxIdArr         = $this->post('mxId') ?: [];
        $materialIdArr   = $this->post('materialId');
        $numArr          = $this->post('num');
        $sourceTableArr        = $this->post('sourceTable');
        $saleOrderIdArr        = $this->post('saleOrderId');
        $moneyArr        = $this->post('money');
        $mxTextArr       = $this->post('mxText');
        $rate = $this->post('rate') ?? 0;
        $field           = [
            'khid'        => $this->post('khid'),
            'invoiceDate' => $this->post('invoiceDate'),
            'type'     => $this->post('type'),
            'invoiceNo'   => $this->post('invoiceNo'),
            'rate'        => $rate,
            'money'       => array_sum($moneyArr),
            'taxMoney'    => array_sum($moneyArr) * $rate,
            'text'        => $this->post('text'),
            'updateTime'  => $this->time,
            'recordDate'  => $this->date,
        ];
        $kehu  = query('kehu', "khid = '$field[khid]'");
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑权限";
        } else {
            $this->startTrans();
            $isPass           = true;//事务通过标志
            if (!$info['id']) {
                $userNo       = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'XSFP' . date('Ymd', strtotime($field['recordDate'])),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => '',
                ], $field);
                $field        = array_merge($field, [
                    'id'      => $id,
                    'coid'    => self::$coid,
                    'orderNo' => $userNo,
                    'state'   => '草稿',
                    'stid'    => $this->control['stid'],
                    'time'    => $this->time,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加或更新明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $numArr[$k]   = self::formattingFigure($numArr[$k] ?? 0, 'numPrecision');
                    $moneyArr[$k] = self::formattingFigure($moneyArr[$k], 'pricePrecision');
                    $material = query('material', " id = '$materialIdArr[$k]'");
                    if (static::total(array('table' => self::tableMx, 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'unit'            => $material['unit'],
                                'materialId'      => $materialIdArr[$k],
                                'num'             => $numArr[$k],
                                'money'           => $moneyArr[$k],
                                'sourceTable'     => $sourceTableArr[$k],
                                'saleOrderId'     => $saleOrderIdArr[$k],
                                'taxMoney'        => 0,//税额
                                'moneyWithOutTax' => 0,//不含税金额
                                'price'           => 0,
                                'text'            => $mxTextArr[$k],
                            ],
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => [
                                'id'              => $nid,
                                'coid'            => self::$coid,
                                'orderId'         => $id,
                                'materialId'      => $materialIdArr[$k],
                                'unit'            => $material['unit'],
                                'num'             => $numArr[$k],
                                'money'           => $moneyArr[$k],
                                'sourceTable'     => $sourceTableArr[$k],
                                'saleOrderId'     => $saleOrderIdArr[$k],
                                'taxMoney'        => 0,//税额
                                'moneyWithOutTax' => 0,//不含税金额
                                'price'           => 0,
                                'text'            => $mxTextArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], "{{staffName}}{{type}}了{{销售报损单}} id：【{{id}}】");
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * @return bool|string
     */
    public function addMx()
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $data             = [
            'material_type'            => "产品",
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = "你还没有编辑权限";
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = "请选择产品";
        } else {
            $json['html'] = '';
            $tr           = [];
            foreach ($mxIdArr as $mxId) {
                $material              = query('material', "id = '$mxId'");
                $id                    = self::getId();
                $material['salePrice'] = $material['salePrice'] ? self::formattingFigure($material['salePrice'], 'pricePrecision') : '';
                $tr[]                  = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'sourceTable[]', 'value' => "")) .
                    hidden(array('name' => 'saleOrderId[]', 'value' => "")) .
                    hidden(array('name' => 'materialId[]', 'value' => $material['id'])),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    "",
                    "",
                    "",
                    text(array('name' => 'money[]', 'value' => '')),
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
                    ""
                ];
            }
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = "未找到销项发票单";
        } else {
            //菜单
            $data = array(
                "id"    => $info['id'],
                "title" => "销项发票单详情",
            );

            $button = [];
            //按钮
            $button[] = [
                "name" => "打印",
                "type" => "点击事件",
                "fun"  => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
            ];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => '复核',
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);
            $kehu        = query('kehu', "khid = '$info[khid]'");
            $tr[]        = [ '产品编码', '产品名称', '规格型号', '单位', '单价', '发货数量', '金额', '本次开票金额', '备注' , '关联单据'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $tr[]     = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $array['price'],
                    $array['num'],
                    self::lostZero($array['num'], 'numPrecision'),
                    self::lostZero($array['money'], 'pricePrecision'),
                    $array['text'],
                    "",
                ];
            }

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "客户"      => $kehu['companyName'],
                        "开票金额"      => $info['money'],
                    ),
                    array(
                        "开票日期"     => $info['invoiceDate'],
                        "发票类型"     => $info['type'],
                    ),
                    array(
                        "发票编号"     => $info['invoiceNo'],
                        "税率"     => $info['rate'],
                    ),
                    array(
                        "税额"     => $info['taxMoney'],
                        "备注"     => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => "明细",
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
}